#!/bin/bash
echo "Create a database dedicated to payment operations recording"
echo ""
echo "Command to use to get a privileged access to the Mysql database (default: 'mysql -u root')"
read MYSQLCMD
if [ "$MYSQLCMD" == '' ]
then
    MYSQLCMD='mysql -u root'
fi
echo "Database name (default : 'caerp_payment')"
read DBNAME
if [ "$DBNAME" == '' ]
then
    DBNAME='caerp_payment'
fi
echo "Specific database user (default : 'caerp_payment')"
read DBUSER
if [ "$DBUSER" == '' ]
then
    DBUSER='caerp_payment'
fi
echo "User's password (default : 'caerp_payment')"
read DBUSER_PWD
if [ "$DBUSER_PWD" == "" ]
then
    DBUSER_PWD="caerp_payment"
fi

result=`echo "Show databases" | ${MYSQLCMD} | grep ${DBNAME}`
if [ "$result" == "${DBNAME}" ]
then
    echo "- ERROR : Database ${DBNAME} already exists"
    exit 1
fi
echo "+ Database doesn't exist yet"
echo "+ Create user ${DBUSER}"
echo "CREATE USER IF NOT EXISTS '${DBUSER}'@'localhost' IDENTIFIED BY \"${DBUSER_PWD};\";" | ${MYSQLCMD}
echo "Done"
echo "+ Create database ${DBNAME}"
echo "CREATE DATABASE ${DBNAME}" | ${MYSQLCMD}
echo "Done"
echo "+ Managing privileges"
echo "GRANT SELECT,INSERT,CREATE,ALTER on ${DBNAME}.* TO '${DBUSER}'@localhost" | ${MYSQLCMD}
echo "Done"
echo "You can put the following connection url in your ini file :"
echo "                  mysql://${DBUSER}:${DBUSER_PWD}@localhost/${DBNAME}?charset=utf8mb4"
exit 0

